package me.jzn.alib.utils;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;

import androidx.annotation.WorkerThread;

import java.util.HashSet;
import java.util.Set;

import me.jzn.alib.ALib;
import me.jzn.core.exceptions.ShouldNotRunHereException;

/**
 * 专门用来播放警报，信息来了等提示音
 */
public class BeepUtil {
    private static SoundPool sBeepSoundPool;
    private static Set<Integer> sSoundIdCache = new HashSet<>(2);
    private static float sBeepVolume = -1;

    /**
     * MeidaPlayer  资源占用量较高、延迟时间较长、不支持多个音频同时播放等
     * SoundPool支持多个音频文件同时播放(组合音频也是有上限的)，延时短，比较适合短促、密集的场景，是游戏开发中音效播放的福音。
     *
     * @param resId: 要么是beep,要么是消息到了dingdong
     */
    @WorkerThread
    public static void playBeep(final int resId, final boolean repeat) {
        if (sBeepSoundPool == null) {
            sBeepSoundPool = genSoundPool();
        }
        if (sBeepVolume < 0) {
            AudioManager mgr = (AudioManager) ALib.app().getSystemService(Context.AUDIO_SERVICE);
            float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
            float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
            sBeepVolume = streamVolumeCurrent / streamVolumeMax;
        }

        ///////////////////////////////////////////////////
        int soundID = sBeepSoundPool.load(ALib.app(), resId, 1);
        sSoundIdCache.add(soundID);
        try {
            Thread.sleep(600);
        } catch (InterruptedException e) {
            throw new ShouldNotRunHereException(e);
        }
        sBeepSoundPool.play(soundID, sBeepVolume, sBeepVolume, 1, repeat ? -1 : 0, 1.0f);// null-pointer
    }

    public static void stopBeep() {
        try {
            for (Integer soundId : sSoundIdCache) {
                sBeepSoundPool.release();
                sBeepSoundPool.stop(soundId);
            }
        } finally {
            sSoundIdCache.clear();
        }
    }

    private static final SoundPool genSoundPool() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AudioAttributes abs = new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
                    .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC).setLegacyStreamType(AudioManager.STREAM_MUSIC)
                    .build();
            return new SoundPool.Builder().setMaxStreams(1)   //设置允许同时播放的流的最大值
                    .setAudioAttributes(abs)   //完全可以设置为null
                    .build();
        } else {
            return new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
        }
    }
}
